package com.leandom.studydemo.activity;

import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import com.leandom.studydemo.R;
import com.leandom.studydemo.contentresolver.TestContentProvider;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 参考https://juejin.im/entry/5726d30e49830c0053562f1a
 */
public class ContentResolverActivity extends AppCompatActivity {

    private static final String TAG = "DEMO";
    private Uri mUri;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_content_resolver);

        mUri = new Uri.Builder()
                .scheme("content")
                .authority(TestContentProvider.CONTENT_AUTHORITY)
                .path(TestContentProvider.PATH_TEST)
                .build();

        findViewById(R.id.btn_insert).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getContentResolver().insert(mUri, null);
            }
        });

        getContentResolver().registerContentObserver(mUri, true, new ContentObserver(new Handler(Looper.getMainLooper())) {
            @Override
            public void onChange(boolean selfChange) {
                Log.d(TAG, "onChange: ");
            }

            @Override
            public void onChange(boolean selfChange, Uri uri) {
                Log.d(TAG, "onChange: " + selfChange + ", " + uri);
            }
        });

        query();
        query2();
        query3();
    }

    private void query() {
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(mUri, null, null, null, null);
        Log.d(TAG, "query: " + mUri);
        if (cursor != null) {
            Log.d(TAG, "query result: " + cursor.getCount());
            // cursor.setNotificationUri(getContentResolver(), mUri);

            cursor.registerContentObserver(new ContentObserver(new Handler()) {
                @Override
                public void onChange(boolean selfChange) {
                    Log.d(TAG, "onChange from cursor: " + selfChange);
                }

                @Override
                public void onChange(boolean selfChange, Uri uri) {
                    // uri is Null
                    Log.d(TAG, "onChange from cursor: " + uri);
                }
            });
        } else {
            Log.d(TAG, "query result is NULL");
        }
    }

    private void query2() {
        ContentProviderClient client = acquireContentProviderClient(TestContentProvider.CONTENT_AUTHORITY);
        try {
            Cursor cursor = client.query(mUri, null, null, null, null);
            Log.d(TAG, "query2: " + cursor.getCount());
            releaseQuietly(client);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void query3() {
        // Pick up provider with action string
        final PackageManager pm = getPackageManager();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            final Intent intent = new Intent("com.leandom.studydemo..action.testProvider");
            final List<ResolveInfo> providers;
            providers = pm.queryIntentContentProviders(intent, 0);
            for (ResolveInfo info : providers) {
                handleProvider(info.providerInfo);
            }
        } else {
            List<ProviderInfo> providers = pm.queryContentProviders(getPackageName(), getApplicationInfo().uid, 0);
            for (ProviderInfo providerInfo : providers) {
                handleProvider(providerInfo);
            }
        }
    }

    private void handleProvider(ProviderInfo providerInfo) {
        ContentProviderClient client = acquireContentProviderClient(providerInfo.authority);
        try {
            Cursor cursor = client.query(mUri, null, null, null, null);
            Log.d(TAG, "query3: " + cursor.getCount());
            releaseQuietly(client);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private ContentProviderClient acquireContentProviderClient(String authority) {
        ContentResolver resolver = getContentResolver();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return resolver.acquireUnstableContentProviderClient(authority);
        } else {
            return resolver.acquireContentProviderClient(authority);
        }
    }

    public static void releaseQuietly(ContentProviderClient client) {
        if (client != null) {
            try {
                client.release();
            } catch (Exception ignored) {
            }
        }
    }

}
